package gw.com.android.ui.me;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import org.json.JSONObject;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;

import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.greendao.NotifyDataHelper;
import gw.com.android.model.ConfigSettingDeal;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.presenter.AdsConfigPresenter;
import gw.com.android.presenter.AdsData;
import gw.com.android.presenter.LoginPresenter;
import gw.com.android.presenter.PhoneLoginPresenter;
import gw.com.android.presenter.PresenterImpl;
import gw.com.android.presenter.SwitchAccountPresenter;
import gw.com.android.presenter.http.HttpCallback;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.MainActivity;
import gw.com.android.ui.bulletin.NotifyCentreActivity;
import gw.com.android.ui.bulletin.NotifyRequest;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.ui.me_concern.MyConcernActivity;
import gw.com.android.ui.me_post.MyPostActivity;
import gw.com.android.ui.system.SystemSettingAdapter;
import gw.com.android.utils.MobclickEventUtlis;
import gw.com.android.utils.PackStatis;
import gw.com.android.utils.PayegisUtil;
import gw.com.android.utils.ThreadPool;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.dialog.ToastPopWindow;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.CommonUtils;
import www.com.library.util.DeviceUtil;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.StringUtils;
import www.com.library.view.BtnClickListener;

/**
 * 我  的 首页
 *
 * @author jett
 * @since 2017-07-28.
 */
public class MeFragment extends PushMsgTabFragment implements View.OnClickListener, PresenterImpl {

    private final int REQUEST_PROFILE = 2;

    private TextView tvBalance, tvSymbol;
    private ImageView ivBalanceEye;
    private DataItemDetail mDepositDetail;
    private DataItemDetail mWithdrawDetail;
    private StretchyHeaderListView mListView;
    private TextView tvNoticeCount;

    private LoginPresenter mPresenter = null;
    private ImageView ivIcon;
    private TextView tvAccount;
    private SystemSettingAdapter mAdapter;
    private SwitchAccountPresenter mSwitchPresenter;
    private ProfileRequest profileRequest;
    private ProfileData mProfile;
    private FrameLayout noviceWelfareLayout;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main_me;
    }

    @Override
    protected void initLayoutView() {
        mListView = (StretchyHeaderListView) mRootView.findViewById(R.id.list_view);
        //去掉箭头
        mListView.setGroupIndicator(null);
        //不可点击收缩
        mListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
        final int accountType = GTConfig.instance().getAccountType();
        if (accountType == GTConfig.ACC_TYPE_GUEST) {
            mHeaderView = View.inflate(getActivity(), R.layout.fragment_main_me_head_guest, null);
            initUnloginView(mHeaderView);
            refreshMeAds();
        } else if (accountType == GTConfig.ACC_TYPE_DEMO) {
            mHeaderView = View.inflate(getActivity(), R.layout.fragment_main_me_head_demo, null);//上半部分
            initLoginedView(accountType);
            setLoginedViewData(accountType);
            refreshMeAds();
        } else {//real
            //判断当前用户是否已实名制的接口
            //进行优化
            loadLoginedViews(accountType);
            requestIfCertification();//初始化的时候调用一次

        }

        // 刷新所有activity底部的系统按钮红点
        new RedPointTask().execute();

        new NotifyRequest().getCategory(null);//取得所有的消息类型，并且注入到本地文件存储起来
    }

    int count = 0;

    /**
     * 请求 当前账户是否已经通过认证
     */
    private void requestIfCertification() {
        Log.d("approvedTag", "start request");
        UploadedFileStatus.getInstance().request(GTConfig.instance().mCurName, new UploadedFileStatus.OnStateListener() {
            @Override
            public void onResponse(final boolean approved) {//这个返回值 true表示已认证，false表示未认证

                AppMain.getApp().getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("approvedTag", "result:" + approved);

                        //进队那两个view进行隐藏和显示的操作
                        View llNotCertification = mHeaderView.findViewById(R.id.ll_not_certification);
                        View ivNotCertification = mHeaderView.findViewById(R.id.iv_not_certification);

//                        if (count == 0) {
                        if (!approved) {//未认证，显示这两个view

                            //突然出现感觉很粗糙，那么现在，加个动画
                            llNotCertification.setVisibility(View.VISIBLE);
                            ivNotCertification.setVisibility(View.VISIBLE);

                            showingAnimator(llNotCertification, DeviceUtil.instance().dip2px(36, getContext()));//这里的36，18，是这两个view在xml里面对应的dp值
                            showingAnimator(ivNotCertification, DeviceUtil.instance().dip2px(18, getContext()));

                            llNotCertification.setOnClickListener(MeFragment.this);
                            ivNotCertification.setOnClickListener(MeFragment.this);
                        } else {//已认证,则隐藏这两个view

                            mHeaderView.getLayoutParams().height = DeviceUtil.instance().dip2px(233, getContext());
                            mHeaderView.requestLayout();//变更高度

                            mListView.setOriHeaderHeight(DeviceUtil.instance().dip2px(233, getContext()));//并且通知listView,确保后续的弹性滑动以这个高度为准

                            llNotCertification.setVisibility(View.GONE);
                            ivNotCertification.setVisibility(View.GONE);
                            llNotCertification.setOnClickListener(null);
                            ivNotCertification.setOnClickListener(null);
                        }
                        count++;
                    }
                }, 0);
            }
        });
    }


    /**
     * 写动画效果，view的高度随着时间而变化，直到 原高度
     */
    private void showingAnimator(final View view, final int oriHeight) {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                view.getLayoutParams().height = (int) (oriHeight * value);
                view.requestLayout();
            }
        });
        valueAnimator.setDuration(500);
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {//动画执行结束，则启用弹性布局的滑动
                super.onAnimationEnd(animation);
                mListView.setIfAllowStretchy(true);
            }

            @Override
            public void onAnimationStart(Animator animation) {//开始执行动画，则禁用弹性布局的滑动
                super.onAnimationStart(animation);
                mListView.setIfAllowStretchy(false);
            }
        });
        valueAnimator.start();
    }

    ImageView iv_bg;
    private View menuView;
    private View mHeaderView;

    private void loadLoginedViews(int accountType) {
        mHeaderView = View.inflate(getActivity(), R.layout.fragment_main_me_head_real, null);//上半部分
        initLoginedView(accountType);
        setLoginedViewData(accountType);
        refreshMeAds();
    }

    private void initUnloginView(View view) {
        view.findViewById(R.id.tv_me_head_login).setOnClickListener(this);
        view.findViewById(R.id.tv_me_head_register).setOnClickListener(this);
        view.findViewById(R.id.iv_me_main_service).setOnClickListener(this);
        view.findViewById(R.id.iv_me_head_icon).setOnClickListener(this);
        mListView.addHeaderView(view);
    }


    private void initLoginedView(int accountType) {
        mListView.removeHeaderView(mHeaderView);
        if (null != menuView)
            mListView.removeHeaderView(menuView);//先移除所有header
        if (null != mHeaderView)
            mListView.removeHeaderView(mHeaderView);//移除头部

        tvAccount = (TextView) mHeaderView.findViewById(R.id.tv_me_head_account);
        ivIcon = (ImageView) mHeaderView.findViewById(R.id.iv_me_head_icon);
        tvBalance = (TextView) mHeaderView.findViewById(R.id.tv_me_head_amount);
        tvSymbol = (TextView) mHeaderView.findViewById(R.id.tv_me_head_amount_symbol);
        ivBalanceEye = (ImageView) mHeaderView.findViewById(R.id.iv_me_main_eye);
        TextView tv_real_demo_switch = (TextView) mHeaderView.findViewById(R.id.tv_real_demo_switch);
        iv_bg = (ImageView) mHeaderView.findViewById(R.id.iv_bg);
        Typeface font = Typeface.createFromAsset(getResources().getAssets(), "fonts/DIN_Medium.ttf");
        tvBalance.setTypeface(font);
        tvSymbol.setTypeface(font);

        if (accountType == GTConfig.ACC_TYPE_REAL) {
            ConfigSettingDeal mSettingDeal = new ConfigSettingDeal();
            mDepositDetail = mSettingDeal.getItemValue(ConfigType.DEPOSIT_TAG);//充值
            mWithdrawDetail = mSettingDeal.getItemValue(ConfigType.DRAW_TAG);//提现
            TextView mWithdrawBtn = (TextView) mHeaderView.findViewById(R.id.tv_me_main_withdraw);
            TextView mDepositBtn = (TextView) mHeaderView.findViewById(R.id.tv_me_main_deposit);
            mWithdrawBtn.setText(mWithdrawDetail.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
            mDepositBtn.setText(mDepositDetail.getString(ConfigType.CONFIG_TYPE_TITLE_TAG));
            mWithdrawBtn.setOnClickListener(this);
            mDepositBtn.setOnClickListener(this);
            mListView.addHeaderView(mHeaderView);//添加两个header

        } else {
            ((TextView) mHeaderView.findViewById(R.id.tv_me_head_property)).setText(R.string.system_demo_assets);
            mListView.addHeaderView(mHeaderView);//添加两个header
        }
        tv_real_demo_switch.setOnClickListener(this);
        mHeaderView.findViewById(R.id.iv_me_main_service).setOnClickListener(this);
        mHeaderView.findViewById(R.id.iv_me_main_eye).setOnClickListener(this);
        tvAccount.setOnClickListener(this);
        ivIcon.setOnClickListener(this);
    }

    /**
     * 加载  我的 菜单栏广告，如果有，就显示咯
     */
    public void refreshMeAds() {
        if (getContext() == null || mListView == null) {
            return;
        }
        AdsData ad = AdsConfigPresenter.getInstance().getAd(AdsConfigPresenter.TYPE_ME_MENU);
        if (ad != null && ad.adPics != null && !ad.adPics.isEmpty()) {
            final AdsData.PicData data = ad.adPics.get(0);
            if (data == null || TextUtils.isEmpty(data.url)) {
                return;
            }
            if (noviceWelfareLayout != null) {
                mListView.removeHeaderView(noviceWelfareLayout);
                noviceWelfareLayout = null;
            }
            ImageView imageView = new ImageView(getContext());
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DeviceUtil.instance().dip2px(46, getContext()));
            params.leftMargin = params.rightMargin = DeviceUtil.instance().dip2px(20, getContext());
            params.bottomMargin = DeviceUtil.instance().dip2px(5, getContext());
//            if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_REAL) {
//                if (menuView != null) {
//                    menuView.findViewById(R.id.menu_divider).setVisibility(View.GONE);
//                }
//            } else {
            params.topMargin = DeviceUtil.instance().dip2px(15, getContext());
//            }
            noviceWelfareLayout = new FrameLayout(getContext());
            noviceWelfareLayout.setBackgroundColor(Color.WHITE);
            noviceWelfareLayout.addView(imageView, params);

            Glide.with(getActivity()).load(data.url).into(imageView);
            mListView.addHeaderView(noviceWelfareLayout);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DataItemDetail detail = new DataItemDetail();
                    detail.setStringValue(ConfigType.CONFIG_TYPE_TYPE_URL_TAG, data.link);
                    detail.setStringValue(ConfigType.CONFIG_TYPE_TITLE_TAG, data.title);
                    ActivityManager.showWebPageActivity(getActivity(), detail, null);
                }
            });
        }
    }

    /**
     * 设置消息数目,超过99（不含99）的，都表示成99+
     */
    private void setNoticeCount(int count) {
        if (tvNoticeCount == null) return;
        if (count <= 0) {
            tvNoticeCount.setVisibility(View.GONE);
            return;
        }
        tvNoticeCount.setVisibility(View.VISIBLE);
        if (count < 100) {
            tvNoticeCount.setText(String.valueOf(count));
        } else {
            tvNoticeCount.setText("99+");
        }
    }

    private void setLoginedViewData(int accountType) {
        showBalance(GTConfig.instance().getBooleanValue(GTConfig.PREF_ASSET_SHOW, true));
        if (accountType != GTConfig.ACC_TYPE_DEMO) {
            if (profileRequest == null) {
                profileRequest = new ProfileRequest();
            }
            ProfileData profileData = profileRequest.fetchLocal();
            refreshProfileView(profileData);
            PhoneNumber.getInstance().acquireAsync(new PhoneNumber.OnPhoneListener() {
                @Override
                public void onSuccess(final String num) {
                    ThreadPool.getInstance().execute(new Runnable() {
                        @Override
                        public void run() {
                            getProfileFromNet(num);
                        }
                    });
                }
            });
        }
    }

    private class RedPointTask extends AsyncTask<Void, Void, Integer> {
        @Override
        protected Integer doInBackground(Void... voids) {
            return NotifyDataHelper.getUnreadCount();
        }

        @Override
        protected void onPostExecute(Integer result) {
            refreshRedPoint(result);
        }
    }

    public void refreshRedPoint(int count) {
//        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_REAL) {
//            setNoticeCount(count);
//        } else {
        if (mAdapter != null) {
            mAdapter.setUnReadCount(count);
            mAdapter.notifyDataSetChanged();
        }
//        }
    }

    private void refreshProfileView(ProfileData data) {
        if (data == null) {
            return;
        }
//        String nickname = TextUtils.isEmpty(data.nickname) ? GTConfig.instance().mCurName : data.nickname;
//        tvAccount.setText(nickname);
        tvAccount.setText(GTConfig.instance().mCurName);// 直接用交易账户名
        int defaultId = data.isFemale() ? R.mipmap.a_profiles_f : R.mipmap.a_show_profiles;
//        if (!TextUtils.isEmpty(data.avatar)) {
//            Drawable drawable = ivIcon.getDrawable();
//            if (drawable != null) {
//                Glide.with(getActivity())
//                        .load(data.avatar)
//                        .placeholder(drawable)
//                        .error(drawable)
//                        .transform(new GlideCircleTransform(getContext()))
//                        .into(ivIcon);
//            } else {
//                Glide.with(getActivity())
//                        .load(data.avatar)
//                        .placeholder(defaultId)
//                        .error(defaultId)
//                        .transform(new GlideCircleTransform(getContext()))
//                        .into(ivIcon);
//            }
//        } else {
//            ivIcon.setImageResource(defaultId);
//        }
        ivIcon.setImageResource(defaultId);// 直接用默认头像
        mProfile = data;
    }

    private void getProfileFromNet(String num) {
        if (profileRequest == null) {
            profileRequest = new ProfileRequest();
        }
        profileRequest.getUserInfo(num, new HttpCallback<ProfileData>() {
            @Override
            public void onSuccess(ProfileData result) {
                refreshProfileView(result);
                profileRequest.cache2Local(result);
            }

            @Override
            public void onFailure(Exception e) {
                Logger.e(e);
            }
        });
    }


    @Override
    protected void initViewData() {
        ConfigSettingDeal mSettingDeal = new ConfigSettingDeal();
        DataItemResult mGroupData = new DataItemResult();
        ArrayList<DataItemResult> mResult = mSettingDeal.getSettingList(mGroupData, ConfigType.SYSTEM_LIST_TAG);
        mAdapter = new SystemSettingAdapter(mGroupData, mResult, getActivity(), this, mSettingDeal);
        mAdapter.setFromMe(true);
        mListView.setAdapter(mAdapter);
        //所有项全部展开
        for (int i = 0; i < mGroupData.getDataCount(); i++) {
            mListView.expandGroup(i);
        }
        mAdapter.setListView(mListView, AppMain.getAppString(R.string.btn_back));
        onSendQuote();
        messageVisibility();
        BaseActivity activity = (BaseActivity) getActivity();
        if (null != activity) {
            activity.setTransparentBar(true);
        }
    }

    @Override
    public void registerRxBus() {
        Disposable accountRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_ACCOUNT_UPDATE + "", DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {

                    @Override
                    public void accept(@NonNull DataItemDetail account) throws Exception {
                        onAccountNotify();
                    }
                });

        bindSubscription(accountRegister);
    }

    /**
     * 刷新消息中心红点
     */
    public void messageVisibility() {
        if (null != mAdapter) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onAccountNotify() {
        super.onAccountNotify();
        showBalance(GTConfig.instance().getBooleanValue(GTConfig.PREF_ASSET_SHOW, true));
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!isHidden()) {
            BaseActivity activity = (BaseActivity) getActivity();
            if (null != activity) {
                activity.setTransparentBar(true);
            }
            onSendQuote();
            showBalance(GTConfig.instance().getBooleanValue(GTConfig.PREF_ASSET_SHOW, true));
        }
    }

    @Override
    public void onSendQuote() {
        AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCode(0));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.iv_me_head_icon:// 取消点击事件
//            case R.id.tv_me_head_account:
//                //switchAccount();
//                if (GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_REAL) {
//                    PackStatis.getToService("clickAccountDemo", "Me", null, null);
//                    new ToastPopWindow(getContext(), getString(R.string.profile_entrance)).show();
//                } else {
//                    PackStatis.getToService("clickAccountReal", "Me", null, null);
//                    startActivityForResult(new Intent(getContext(), ProfileActivity.class), REQUEST_PROFILE);
//                }
//                break;
            case R.id.iv_me_main_service:
                PackStatis.getToService("clickService", "Me", null, null);
                ConfigSettingDeal mDeal = new ConfigSettingDeal();
                if (ConfigUtil.instance().customerFunction() == 2) {
                    mDeal.openContact(getActivity(), ConfigType.QUOTE_CONTACT_TAG);
                } else {
                    mDeal.openQQ(getActivity(), ConfigType.QQ_SOURCE_ME);
                }
                break;
            case R.id.iv_me_main_eye:
                if (!DataManager.instance().hasAccount()) {
                    return;
                }
                boolean showAsset = GTConfig.instance().getBooleanValue(GTConfig.PREF_ASSET_SHOW, true);
                showBalance(!showAsset);
                if (!showAsset) {
                    PackStatis.getToService(PackStatis.EventAction.CLICKEYE.getValue(), PackStatis.EventCategory.ME.getValue(), null, "2");
                } else {
                    PackStatis.getToService(PackStatis.EventAction.CLICKEYE.getValue(), PackStatis.EventCategory.ME.getValue(), null, "1");
                }
                GTConfig.instance().setBooleanValue(GTConfig.PREF_ASSET_SHOW, !showAsset);
                break;
            case R.id.tv_me_main_withdraw:// 提现按钮
                PackStatis.getToService(PackStatis.EventAction.CLICKOUTCOME.getValue(), PackStatis.EventCategory.ME.getValue(), null, null);
                ActivityManager.showWebPageActivity(getActivity(), mWithdrawDetail, AppMain.getAppString(R.string.btn_back));
                break;
            case R.id.tv_me_main_deposit:
                PayegisUtil.trackEvent("deposit");
                PackStatis.getToService("ClickIncomeMoney", "RiskControl", null, null);
                ActivityManager.showWebPageActivity(getActivity(), mDepositDetail, AppMain.getAppString(R.string.btn_back));
                break;
            case R.id.tv_me_head_login:
                PackStatis.getToService("clickLogin", PackStatis.EventCategory.ME.getValue(), null, null);
                if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {
                    GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_REAL);
                    ActivityManager.backLogin(getActivity(), false);
                }
                break;
            case R.id.tv_me_head_register:
                PackStatis.getToService("clickSignUp", PackStatis.EventCategory.ME.getValue(), null, null);
                if (CommonUtils.isFastDoubleClick()) {
                    return;
                }
                ActivityManager.showOpenAccount(getActivity(), ConfigType.ADD_LOGIN_REAL_TAG);
                break;
            case R.id.ll_my_concern:
            case R.id.ll_my_notice:
            case R.id.ll_my_post:
                checkIfAllowClick(v.getId());
                break;
            case R.id.tv_real_demo_switch:
                if (!NetworkMonitor.hasNetWork()) {
                    return;
                }
                if (CommonUtils.isFastDoubleClick()) {
                    return;
                }
                mSwitchPresenter = new SwitchAccountPresenter(getActivity(), MeFragment.this);
                if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_REAL) {
                    PackStatis.getToService("clickToDemo", "Me", null, null);
                    mSwitchPresenter.AccAccountSwitch(GTConfig.ACC_TYPE_DEMO, GTConfig.FROM_QUOTE);
                } else {
                    PackStatis.getToService("clickToReal", "Me", null, null);
                    mSwitchPresenter.AccAccountSwitch(GTConfig.ACC_TYPE_REAL, GTConfig.FROM_QUOTE);
                }
                break;
            case R.id.ll_not_certification:
            case R.id.iv_not_certification:
                requestIfCertification();//点击事件上在调用一次
                //实名制H5的跳转链接
                DataItemDetail item = new ConfigSettingDeal().getItemValue(ConfigType.MY_BANK_INFO_TAG);
                item.setStringValue(ConfigType.CONFIG_TYPE_TITLE_TAG, "实名认证");
                ActivityManager.showWebPageActivity(getActivity(), item, null);
                break;
            default:
                break;
        }
    }

    private void switchAccount() {
        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {
            GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_REAL);
            MobclickEventUtlis.MobclickEventByAccountType(getActivity(), "me_Login");
            ActivityManager.backLogin(getActivity(), false);
        } else {
            if (mPresenter == null || !mPresenter.isLoading) {
                mPresenter = new LoginPresenter(getActivity());
                mPresenter.showChangePop(getActivity(), this);
            } else {
                Logger.e("切换账号 isLoading is true");
            }
        }
        MobclickEventUtlis.MobclickEventByAccountType(getActivity(), "me_assets_btn");
    }

    /**
     * 显示余额
     */
    private void showBalance(boolean show) {
        if (ivBalanceEye != null && tvBalance != null) {
            boolean hasAccount = DataManager.instance().hasAccount();
            if (show) {
                ivBalanceEye.setImageResource(R.mipmap.a_me_eye_moninvisible);
                tvSymbol.setText(hasAccount ? "$" : "");
                tvBalance.setText(hasAccount ? getBalance() : "--");
            } else {
                ivBalanceEye.setImageResource(R.mipmap.a_me_eye_monvisible);
                tvSymbol.setText("");
                tvBalance.setText(hasAccount ? "* * * *" : "--");
            }
            if ("".equals(GTConfig.instance().mCurName)) {
                GTConfig.instance().mCurName = DataManager.instance().mAccount.getString(GTSConst.JSON_KEY_NAME);
            }
            if (mProfile == null || TextUtils.isEmpty(mProfile.nickname)) {
                tvAccount.setText(GTConfig.instance().mCurName);
            }
        }
    }

    /**
     * 获取格式化的余额
     */
    private String getBalance() {
        String amount = DataManager.instance().mAccount.getString(GTSConst.JSON_KEY_BALANCE);
        try {
            double balance = Double.valueOf(amount);
            if (balance == 0) {
                return "0.00";
            }
            return NumberFormat.getNumberInstance(Locale.getDefault()).format(balance);//千位符分隔数字
        } catch (Throwable t) {
            return amount;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_PROFILE) {
            // 从个人详情页回来 后，更新昵称，头像！   使用观察者模式更佳。。。
            AppMain.getApp().getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (profileRequest == null) {
                        profileRequest = new ProfileRequest();
                    }
                    ProfileData profile = profileRequest.fetchLocal();
                    refreshProfileView(profile);
                }
            }, 800);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onRequestSuc(Object result) {
        if (!isVisible()) {
            Logger.e("切换账号 isVisible is false");
            return;
        } else {
            Logger.e("切换账号 isVisible is true");
        }

        final MainActivity mainActivity = (MainActivity) getActivity();
        if (mainActivity != null) {
            mainActivity.hideLoading();
            mainActivity.removeAllFragment(false, true);
            AppMain.getApp().getHandler().post(new Runnable() {
                @Override
                public void run() {
                    mainActivity.showMeFragment();
                }
            });
        } else {
            Logger.e("切换账号 getActivity() is null");
        }
        AppTerminal.instance().setLoginView(0);
        if (null != mPresenter) {
            mPresenter.isLoading = false;
            mPresenter.setPresenterImpl(null);
            mPresenter = null;
        }
        if (null != mSwitchPresenter) {
            mSwitchPresenter.clearData();
            mSwitchPresenter = null;
        }
    }

    @Override
    public void onRequestFail(int failCode) {
        final BaseActivity mActivity = (BaseActivity) getActivity();
        if (null != mActivity) {
            mActivity.hideLoading();
            if (failCode == 1 || failCode == 34) {
                return;
            }
            String error;
            if (failCode >= 1100 && failCode < 1200) {
                error = ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1100) + failCode;
            } else {
                error = ConfigUtil.instance().getErrorConfigObject().optString(failCode + "");
            }
            PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(mActivity, error, new BtnClickListener() {
                @Override
                public void onBtnClick(int viewID) {
                    GTConfig.instance().isPhoneLogin = false;
                    GTConfig.instance().mCurLoginPhone = "";
                    ActivityManager.backLogin(mActivity, true);
                }
            });
            dialog.setCancelable(false);
            dialog.show();
        }
        if (null != mPresenter) {
            if (GTConfig.instance().getBooleanValue(GTConfig.PREF_AUTO_LOGIN)) {
                GTConfig.instance().setBooleanValue(GTConfig.PREF_AUTO_LOGIN, false);
            }
            GTConfig.instance().isFromLogin = false;
            GTConfig.instance().mUserPwd = "";
            mPresenter.isLoading = false;
            mPresenter.setPresenterImpl(null);
            mPresenter = null;
        }
        if (null != mSwitchPresenter) {
            mSwitchPresenter.clearData();
            mSwitchPresenter = null;
        }

    }

    private DataItemDetail mAccountInfo;

    private void checkIfAllowClick(final int viewId) {
        //如果是模拟用户登录，那么，查询当前模拟用户是否关联了真实用户
        //如果关联了，就返回true，否则false
        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_DEMO) {
            int mSeq = GTSDataListener.curSeq++;
            String loginPass = GTConfig.instance().mUserPwd;
            mAccountInfo = DataManager.instance().mAccount;
            String loginPhoneNo = mAccountInfo.getString(GTSConst.JSON_KEY_PHONE);
            if (!StringUtils.isEmpty(loginPhoneNo)) {
                if (loginPhoneNo.startsWith("86")) {
                    loginPhoneNo = loginPhoneNo.substring(2, loginPhoneNo.length());
                }
            }
            Log.d("checkDemoTagParam", "" + mSeq + " - " + loginPhoneNo + "-" + loginPass);
            PhoneLoginPresenter.instance().PhoneLoginFun(AppContances.NORMALREQ_TYPE_GET_CUSTOMERBYMOBILE, mSeq, loginPhoneNo, loginPass,
                    new PhoneLoginPresenter.OnMobileReqResultListener() {
                        @Override
                        public void reqResultSuccess(Object mObject) {
                            JSONObject obj = (JSONObject) mObject;
                            JSONObject result = obj.optJSONObject("result");
                            if (!result.isNull("customerNumber") && !result.isNull("demoCustomerNumber")) {//就是没有绑定
                                String customerNumber = result.optString("customerNumber");
                                Log.d("checkDemoTag", "当前登录的是模拟账户,已绑定真实帐户:" + customerNumber);

                                //如果已经绑定了真实账户，那就让我的关注显示 真实账户的关注数据
                                executeClick(viewId);
                            } else {
                                Log.d("checkDemoTag", "当前登录的是模拟账户并且没有绑定真实账户");
                                //如果没有绑定，
//                                那就不让点, 点了没用
                                new ToastPopWindow(getContext(), "只对真实用户开放哦~\n 请补充资料，开通真实账号。").show();
                            }
                        }

                        @Override
                        public void reqResultFail(int failCode) {
                            Log.d("checkDemoTag", "请求失败");
                        }
                    });
        } else {
            executeClick(viewId);
        }
    }

    private void executeClick(int viewId) {
        switch (viewId) {
            case R.id.ll_my_concern:
                PackStatis.getToService("clickMyConcern", PackStatis.EventCategory.ME.getValue(), null, null);
                startActivityForResult(new Intent(getContext(), MyConcernActivity.class), REQUEST_PROFILE);
                break;
            case R.id.ll_my_notice:
                Intent intent = new Intent(getActivity(), NotifyCentreActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.ll_my_post:
                PackStatis.getToService("clickMyPosts", PackStatis.EventCategory.ME.getValue(), null, null);
                startActivityForResult(new Intent(getContext(), MyPostActivity.class), REQUEST_PROFILE);
                break;
        }
    }
}
